package com.xwaf.platform.web.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.base.Preconditions;
import com.xwaf.platform.common.utils.annotation.CurrentLimitRequired;
import com.xwaf.platform.system.api.service.gateway.CurrentLimitService;

public class CurrentLimitRequiredInterceptor implements HandlerInterceptor {

	private final CurrentLimitService currentLimitService;

	public CurrentLimitRequiredInterceptor(CurrentLimitService currentLimitService) {
		this.currentLimitService = Preconditions.checkNotNull(currentLimitService,
				"the 'currentLimitServ' argument must not be null");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod h = (HandlerMethod) handler;
			CurrentLimitRequired currentLimit = h.getMethodAnnotation(CurrentLimitRequired.class);
			if (null != currentLimit) {
				final String uid = request.getParameter("uid");
				final String deviceType = request.getParameter("deviceType");
				if (StringUtils.isNotEmpty(uid) && StringUtils.isNotEmpty(deviceType)) {
					// 处理限流
					String uri = request.getRequestURI();
					currentLimitService.currentLimit(uri, uid, deviceType, currentLimit.limit(), currentLimit.limit1m(),
							currentLimit.clearTokenNum());
				}
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// nothing yet
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// nothing yet
	}
}
